package com.lxj.security.controller;

import com.lxj.security.service.SecurityService;
import com.lxj.utils.common.CommonResult;
import com.lxj.utils.entity.LoginParam;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;

import java.util.HashMap;

@RestController
@RequestMapping("/security")
public class SecurityController {
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private SecurityService securityService;

    @PostMapping("/login")
    public CommonResult login(LoginParam loginParam) {
        HashMap<String, Object> map = new HashMap<>();
        Jedis jedis = new Jedis();
        String code = jedis.get("code");
        boolean equals = StringUtils.equals(code, loginParam.getCode());
        if (equals) {
            CommonResult login = securityService.login(loginParam);
            map.put("tokenHead", tokenHead);
            map.put("access_token", login.getData());
            jedis.set("username", loginParam.getUsername());
            return CommonResult.success(map);
        } else {
            return CommonResult.failed("验证玛错误");
        }

    }

    @PostMapping("/logout")
    public CommonResult logout(String username) {
        return securityService.logout(username);
    }

    @PostMapping("/getName")
    public CommonResult getName() {
        Jedis jedis = new Jedis();
        String username = jedis.get("username");
        return CommonResult.success(username);
    }
}
